#!coding=utf-8
import time
import hashlib
from shop import settings
from xml.etree import ElementTree
from random import Random
import requests

def getNoncestr(randomlength=16):
    str = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str+=chars[random.randint(0, length)]
    return str

def getpaysign(type,openid,tradeno,ip,fee):
#     stringA="appid=你的appid&body=取个支付名称&mch_id=你的mch_id&nonce_str=随机串&notify_url=支付完成后通知地址&openid=刚刚获取的openid&out_trade_no=刚刚设置的out_trade_no&spbill_create_ip=用户的ip&total_fee=此次支付的费用&trade_type=JSAPI"
    noncestr=getNoncestr();
    msg={}
    #订单号前加了随机机制，方式微信后台判断重复
    #type判断是订单支付，还是买卡券支付，以便在回调接口时的处理
    tradeno=type+noncestr+str(tradeno)
#     print tradeno
    timestamp=int(time.time())
    string="appid=%s&body=%s&mch_id=%s&nonce_str=%s&notify_url=%s&openid=%s&out_trade_no=%s&spbill_create_ip=%s&total_fee=%s&trade_type=JSAPI&key=%s" \
            %(settings.WEIXIN_APPID,settings.WX_body,settings.WX_mch_id,noncestr,settings.WX_notify_url,openid,tradeno,ip,fee,settings.WX_pay_key)
    sign=hashlib.md5(string.encode('utf-8')).hexdigest().upper() 
    
    pay_xml="<xml><appid>"+settings.WEIXIN_APPID+"</appid><body>"+settings.WX_body+"</body><mch_id>"+settings.WX_mch_id+"</mch_id><nonce_str>"+noncestr+"</nonce_str><notify_url>"+settings.WX_notify_url+"</notify_url><openid>"+openid+"</openid><out_trade_no>"+str(tradeno)+"</out_trade_no><spbill_create_ip>"+str(ip)+"</spbill_create_ip><total_fee>"+str(fee)+"</total_fee><trade_type>JSAPI</trade_type><sign>"+sign+"</sign></xml> "
    url="https://api.mch.weixin.qq.com/pay/unifiedorder"
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data=pay_xml.encode('utf-8'), headers=headers)
    xml_elem = ElementTree.fromstring(response.content)
    for child in xml_elem:
        msg[child.tag] = child.text
#         print child.tag,child.text
    package="prepay_id="+msg["prepay_id"]
    stringB="appId="+settings.WEIXIN_APPID+"&nonceStr="+noncestr+"&package="+package+"&signType=MD5&timeStamp="+str(timestamp)+"&key="+settings.WX_pay_key
    paysign=hashlib.md5(stringB.encode('utf-8')).hexdigest().upper()  
    
    paydata={};
    paydata["appId"]=settings.WEIXIN_APPID
    paydata["timeStamp"]=timestamp
    paydata["nonceStr"]=noncestr
    paydata["package"]=package
    paydata["signType"]="MD5"
    paydata["paySign"]=paysign
    
    return paydata
    
    